let fs = require('fs')
const http = require('https')
const cherrio = require('cheerio')
const url = require('url')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/movie', {
    useUnifiedTopology: true,
    useNewUrlParser: true
})
let db = mongoose.connection; //数据库连接对象
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function () {
    console.log('数据库连接成功');
})
//schema对象
//创建一个和集合相关的schema对象 类似表头
// let schema = mongoose.Schema
let userSchema = new mongoose.Schema({
    rate: String,
    title: String,
    url: String,
    id: String,
    imgUrl: String,
    genres: Array
})

let User = mongoose.model('top250', userSchema);

// module.exports = function (app){

//     app.get('/', (req, res) => {
//         fs.readFile('./db.json' , 'UTF-8',(err ,data)=>{
//             //文件中读取出来的一定是字符串 ， 需要转化成对象
//             if(err){
//                 return res.status(500).send('内容服务器错误 ， 请联系管理人员')
//             }
//             // console.log(typeof data);//拿到字符串
//             // {
//             //     "students": [
//             //         {"id":1,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":2,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":3,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":4,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":5,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":6,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":7,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"}
//             //     ]
//             // }
//             res.render('index.html', {
//                 Form: ['地区', '男女比例', '年龄统计', '分数分布'],
//                 students: JSON.parse(data).students//将data字符串转成对象
//             })
//         })   
//     })
// }
const express = require('express')

//创建路由容器
const router = express.Router()

router.get('/', (req, res) => {
    res.redirect('/students')
})
// router.get('/students/addStu', (req, res) => {
//     res.render('addStudent.html')
// })
// router.post('/students/addStu', (req, res) => {
//     let data = req.body
//     let str = JSON.stringify(data)
//     console.log(data);
//     console.log(str);

//     console.log(typeof data);
//     // fs.appendFile('./db.json' ,str,(err,data)=>{
//     //     if(err){
//     //         console.log(err);

//     //     }
//     // })


// })
// router.get('/students', (req, res) => {
//     fs.readFile('./db.json', 'UTF-8', (err, data) => {
//             //文件中读取出来的一定是字符串 ， 需要转化成对象
//             if (err) {
//                 return res.status(500).send('内容服务器错误 ， 请联系管理人员')
//             }
//             // console.log(typeof data);//拿到字符串
//             // {
//             //     "students": [
//             //         {"id":1,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":2,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":3,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":4,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":5,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":6,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"},
//             //         {"id":7,"name":"张三","gender":0,"age":18,"hobbies":"ABCD"}
//             //     ]
//             // }
//             res.render('index.html', {
//                 Form: ['地区', '男女比例', '年龄统计', '分数分布'],
//                 students: JSON.parse(data).students //将data字符串转成对象
//             })
//         })
router.get('/data', (req, res) => {

    fs.readFile('./data.json', 'utf-8', (err, data) => {
        if (err) {
            console.log(err);

        }
        console.log(typeof data);

        res.send(JSON.parse(data))
    })
})
// })
router.get('/movies', (req, res) => {

    fs.readFile('./movies.json', 'utf-8', (err, data) => {
        if (err) {
            console.log(err);

        }
        console.log(typeof data);

        res.send(JSON.parse(data))
    })
})

router.get('/top250', (req, res) => {

    fs.readFile('./top250.json', 'utf-8', (err, data) => {
        if (err) {
            console.log(err);

        }
        console.log(typeof data);

        res.send(JSON.parse(data))
    })
})
router.get('/search', (req, response) => {


    let movieName = url.parse(req.url, true).query.movieName
    console.log(movieName);

    console.log(typeof movieName);


    let searchUrl = `https://m.douban.com/search/?query= ${movieName}`;
    // let json = 'http://nodejs.org/dist/index.json';
    let data = ''
    let results = []
    http.get(searchUrl, (res) => {
        //安全判断
        const {
            statusCode
        } = res; //z状态码
        const contentType = res.headers['content-type']; //文件类型

        console.log(statusCode, contentType);

        let err = null;
        if (statusCode !== 200) {
            err = new Error('请求状态错误')
        } else if (!/^text\/html/.test(contentType)) {
            err = new Error('请求类型错误')
        }
        if (err) {
            console.log(err);
            res.resume(); //重置缓存
            return;
        }
        //数据分段 ， 只要接收数据就会触发data事件 ， chunk表示每次接收的数据片段
        res.on('data', chunk => {
            // console.log('-----数据传输-----');
            // console.log(chunk.toString());
            data += chunk.toString();
        })
        //数据流传输完毕
        res.on('end', () => {
            let $ = cherrio.load(data) //告诉cheerio要加载哪一个html
            let duqu = $('.search_results_subjects li ')
            duqu.each(function (i, elem) {
                let href = $(this).find('a').attr('href')
                let imgUrl = $(this).find('img').attr('src')
                let title = $(this).find('.subject-title').text()
                let rate = $(this).find('p').children('span').attr('data-rating')
                results.push({
                    href: 'https://m.douban.com' + href,
                    imgUrl: imgUrl,
                    title: title,
                    rate: rate / 10
                })
            })

            // fs.writeFile('./results.json',JSON.stringify(results) ,(err)=>{
            //     if(err){
            //         console.log('写入失败');

            //     }
            // })
            response.send(results)

        })
    }).on('error', err => {
        console.log('出错' + err);
        response.send({
            mag: 'Error',
            err: err
        })
    })


})

router.get('/type', (req, res) => {
    let geners = url.parse(req.url, true).query.geners
    console.log(geners);
    if (geners == '全部') {
        User.find({}, (err, data) => res.send(data))
        return
    }

    User.find({
        "genres": `${geners}`
    }, function (err, data) {
        if (err) {
            console.log(err);
        }
        if (data.length != 0) {
            res.send(data)
        } else {
            res.send('无数据')
        }

    })
})
//导出router
module.exports = router